package csc.nndp.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import csc.nndp.dao.User;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/FileUpload")
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private static String TMP_DIR_PATH = "";
	private File tmpDir;
	private static String DESTINATION_DIR_PATH ="";
	private File destinationDir;
	private Integer sizeThreshold;
	private long limitCapacity;
    /**
     * @see HttpServlet#HttpServlet()
     */
	
    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
            }
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		sizeThreshold = Integer.valueOf(getServletConfig().getInitParameter("sizeThreshold"));
		limitCapacity = Integer.valueOf(getServletConfig().getInitParameter("limitCapacity"));
		limitCapacity = limitCapacity*1024*1024;
	}
 

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out=response.getWriter();
		response.setContentType("text/plain");
		
		HttpSession session = request.getSession();
		User user=(User) session.getAttribute("user");
		if(user == null){
			throw new ServletException("Required to login");
		}
		TMP_DIR_PATH = "user/"+user.getUserName()+"/tmp";
		DESTINATION_DIR_PATH="users/" +user.getUserName()+"/upload-folder";
		
		String realTmpPath = getServletContext().getRealPath(TMP_DIR_PATH);
		tmpDir = new File(realTmpPath);
		if(!tmpDir.isDirectory()) {
			tmpDir.mkdirs();
		}
		
		String realUploadPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realUploadPath);
		if(!destinationDir.isDirectory()) {
			destinationDir.mkdirs();
		}
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		
		fileItemFactory.setSizeThreshold(sizeThreshold*1024*1024);
		
		fileItemFactory.setRepository(tmpDir);
		
		ServletFileUpload uploadHander = new ServletFileUpload(fileItemFactory);
		try{
			//parse the request to get the files
			List items = uploadHander.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if(item.getSize() > limitCapacity){
					throw new ServletException(item.getName()+ "[" + item.getSize()/1024/1024+"MB] exceed limit capacity " 
							+limitCapacity/1024/1024);
				}

				//Write file to the real Dir.
				File file = new File(destinationDir,item.getName());
				item.write(file);
				
				out.print("Uploaded successfully. Field Name = "+item.getFieldName()+
						", File Name = "+item.getName()+
						", Content type = "+item.getContentType()+
						", File Size = "+item.getSize());
				out.println("Destination Dir: " + destinationDir);
			}
			
		}catch(FileUploadException ex){
			log("Error encountered whilt parsing the request",ex);
			throw new ServletException(ex.getMessage());
		}catch(Exception ex){
			log("Error encountered while uploading file",ex);
			throw new ServletException(ex.getMessage());
		}finally{
			out.close();
			try{
				deleteTmpFiles(tmpDir);
			}catch (Exception e){
				throw new ServletException(e.getMessage());
			}
		}
		
	}


private void deleteTmpFiles(File tmpDir) throws Exception{
	// Get all files in directory
	File[] files = tmpDir.listFiles();
	for (File file : files){
		// Delete each file
		if (!file.delete()){
			// Failed to delete file
			throw new Exception("Failed to delete "+file);
		}
	}
	
}
}